<?php

namespace App\Http\Controllers\School;

use App\Http\Requests\School\EditRole;
use App\Http\Requests\School\StoreRole;
use App\Http\Resources\RoleResource;
use App\Models\SchoolAdminLog;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Illuminate\Http\Request;

/**
 * Class RoleController
 * @package App\Http\Controllers\School
 */
class RoleController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $roles = Role::query()->latest()
            ->where('guard_name', 'school')
            ->with('permissions')
            ->where("school_id", \Auth::user()->school_id)
            ->when($label = $request->label, function ($query) use ($label) {
                $query->where('label', $label);
            })->paginate($request->size);
        return RoleResource::collection($roles);
    }

    /**
     * @param StoreRole $request
     * @return RoleResource
     */
    public function store(StoreRole $request)
    {
        $role = Role::create([
            'name' => md5(uniqid(microtime(true), true)),
            'label' => $request->label,
            'description' => $request->description,
            'guard_name' => 'school',
            'school_id' => \Auth::user()->school_id
        ]);
        $role->save();
        $permissions = Permission::whereIn('id', $request->permissions)->get();
        $role->syncPermissions($permissions);
        SchoolAdminLog::Log('新增权限组: ' . $role->label);
        return new RoleResource($role);
    }

    /**
     * @param EditRole $request
     * @param Role $role
     * @return RoleResource
     */
    public function update(EditRole $request, Role $role)
    {
        $role->label = $request->label;
        $role->description = $request->description;
        $role->save();
        $permissions = Permission::whereIn('id', $request->permissions)->get();
        $role->syncPermissions($permissions);
        SchoolAdminLog::Log('编辑权限组: ' . $role->label);
        return new RoleResource($role);
    }

    /**
     * @param Role $role
     * @return RoleResource
     * @throws \Exception
     */
    public function destroy(Role $role)
    {
        $role->delete();
        SchoolAdminLog::Log('删除权限组: ' . $role->label);
        return new RoleResource($role);
    }
}
